<!--
 * @Date: 2022-04-09 14:54:47
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-07-15 12:32:24
 * @FilePath: \imitation-microblog-vue\src\components\settingUserInfo.vue
 * @Description: something
-->
<template>
  <div class="baseSetting">
    <div>个人资料设置</div>
    <div class="avatarBox">
      <el-upload
        class="avatar-uploader"
        action="/api/upload"
        ref="uploador"
        :auto-upload="false"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :on-change="handleChange"
      >
        <img :src="settingInfo.avatar" class="avatar" />
        <i class="iconfont icon-jia"></i>
      </el-upload>
      <i>上传图片不超过0.8M</i>
    </div>
    <div class="InputArea">
      <el-form
        label-position="top"
        label-width="100px"
        style="max-width: 460px"
        :model="settingInfo"
        ref="ruleFormRef"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="settingInfo.userName" maxlength="30" />
          <i class="tips">4～30个字符，支持中英文、数字</i>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="settingInfo.nickName" maxlength="30" />
          <i class="tips">4～30个字符，支持中英文、数字</i>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="settingInfo.description" maxlength="140" />
          <i class="tips">1～140个字符</i>
        </el-form-item>
        <el-form-item label="选择性别" prop="gender">
          <el-radio-group v-model="settingInfo.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择所在地" prop="city">
          <choose-city
            @changeCity="changeCity"
            @changProvince="changProvince"
            ref="chooseCityEl"
            :cityRes="settingInfo.city"
          ></choose-city>
        </el-form-item>
      </el-form>
    </div>
    <div class="oprationBtn">
      <div class="submit" @click="submitForm(ruleFormRef)">提交</div>
      <div class="reset" @click="resetForm(ruleFormRef)">重置</div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import type { UploadProps, UploadInstance, UploadFile } from "element-plus";
import { ElMessage } from "element-plus";
import { SettingInfoType } from "../views/Setting/types";
import {
  ref,
  reactive,
  computed,
  onMounted,
  getCurrentInstance,
  watch,
} from "vue";
import chooseCity from "@/components/chooseCity/chooseCity.vue";
import { City } from "../components/chooseCity/type";
import { useStore } from "vuex";
import type { FormInstance } from "element-plus";
import { useRouter } from "vue-router";
let uploador = ref<UploadInstance>();
const { $api } = getCurrentInstance()!.appContext.config.globalProperties!;
const ruleFormRef = ref<FormInstance>();
const chooseCityEl = ref();
let isUploaded = ref(false);
let avatarChange = ref(false);
const store = useStore();
const router = useRouter();
let imageUrl = ref("");
let settingInfo = reactive<SettingInfoType>({
  userName: "",
  nickName: "",
  description: "",
  gender: "3",
  city: "",
  avatar: "",
});
const rules = reactive({
  userName: [{ required: true, message: "用户名不可为空", trigger: "blur" }],
  nickName: [{ required: true, message: "昵称不可为空", trigger: "blur" }],
});
let UserInfo = computed(() => store.state.userInfos);
const handleAvatarSuccess: UploadProps["onSuccess"] = async (
  response,
  uploadFile,
) => {
  if (response.code == 200) {
    isUploaded.value = true;
    settingInfo.avatar = response.data.url;
    let res = await $api.user.reqUpdateUserInfo(settingInfo.id, settingInfo);
    if (res.code == 200) {
      isUploaded.value = false;
      ElMessage.success("更新成功！");
      getUserInfo();
    }
  } else {
    return;
  }
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("仅支持jpg格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 0.8) {
    ElMessage.error("上传文件大小不能超过0.8MB!");
    return false;
  }
  return true;
};
const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  if (uploadFile.size / 1024 / 1024 > 0.8) {
    ElMessage.error("上传文件大小不能超过0.8MB!");
    return false;
  } else {
    if (!isUploaded.value) {
      avatarChange.value = true;
      settingInfo.avatar = URL.createObjectURL(uploadFile.raw!);
    }
  }
  if (uploadFiles.length == 1) {
    uploadFiles = uploadFiles;
  } else {
    let choose: UploadFile = uploadFiles.pop() as UploadFile;

    uploadFiles.length = 0;
    uploadFiles.push(choose);
  }
};
const changeCity = (val: City) => {
  settingInfo.city = val.name;
};
const changProvince = (val: string) => {
  settingInfo.city = val;
};
const getUserInfo = async () => {
  let res = await $api.user.reqUserInfo();
  if (res.code == 200) {
    store.commit("updateUserInfo", res.data);
    router.push({ name: "Home" });
  }
};
//更新用户信息
const getUpdateUserInfo = async (id: number, data: SettingInfoType) => {
  let res = await $api.user.reqUpdateUserInfo(id, data);
  if (res.code == 200) {
    getUserInfo();
  }
};
const init = () => {
  settingInfo.city = UserInfo.value.city;
  settingInfo.userName = UserInfo.value.userName;
  settingInfo.nickName = UserInfo.value.nickName;
  settingInfo.description = UserInfo.value.description;
  settingInfo.avatar = UserInfo.value.avatar;
  settingInfo.gender = UserInfo.value.gender;
};
onMounted(() => {
  init();
});
//表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  chooseCityEl.value.resetResult();
};
//表单提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      settingInfo.id = UserInfo.value.id;
      if (avatarChange.value) {
        await uploador.value!.submit();
      } else {
        let res = await $api.user.reqUpdateUserInfo(
          settingInfo.id,
          settingInfo,
        );
        if (res.code == 200) {
          isUploaded.value = false;
          ElMessage.success("更新成功！");
          getUserInfo();
        }
      }
    } else {
      return false;
    }
  });
};
</script>
<style lang="less" scoped>
.baseSetting {
  // height: 300px;
  border-bottom: 1px solid #f9f9f9;
  padding-top: 20px;

  .avatarBox {
    margin: 20px 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .avatar-uploader {
      width: 100px;
      height: 100px;
      border-radius: 100px;
      background-color: #fafafa;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      position: relative;
      margin: 0 auto;

      .iconfont {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }

      .avatar {
        display: block;
        width: 100%;
        height: 100%;
        z-index: 10;
        &:hover {
          filter: brightness(70%);
        }
      }
    }
    i {
      margin-top: 5px;
      color: #939393;
      font-size: 12px;
      text-align: center;
    }
  }

  .InputArea {
    display: flex;
    justify-content: center;
    align-items: center;

    :deep(.el-form) {
      flex: 1;

      .el-form-item {
        .el-input {
          &:focus {
            border: 1px solid red !important;
          }

          .el-input__inner {
            background-color: #f0f1f4;
            border-radius: 10px;
          }
        }
      }

      .tips {
        font-size: 12px;
        color: #939393;
      }
    }
  }
}

.passwordSetting {
  .InputArea {
    margin-top: 20px;
    margin-bottom: 20px;
  }
}

.oprationBtn {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 50px;

  .submit,
  .reset {
    padding: 8px 25px;
    margin: 0 10px;
    border: 1px solid #ff8303;
    border-radius: 20px;
    font-size: 13px;
    cursor: pointer;

    &:hover {
      color: #fff;
      background-color: #ff8303;
    }
  }

  .reset {
    border: 1px solid #939393;

    &:hover {
      color: #fff;
      background-color: #939393;
    }
  }
}
</style>
